﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using Corina.Infrastructure;

namespace Corina.Utilities
{
    public class InstanceHelper
    {
        private static Dictionary<string, BaseClass> _instance;
        public static Service GetInstance<Service>() where Service : BaseClass
        {
            _instance = null;
            Service instance = null;
            Type type = typeof(Service);
            string typeName = type.Name;
            if (_instance == null)
            {
                _instance = new Dictionary<string, BaseClass>();
            }
            if (_instance.Keys.Contains(typeName))
            {
                instance = _instance[typeName] as Service;
            }
            else
            {
                instance = type.Assembly.CreateInstance(type.FullName) as Service;
                _instance[typeName] = instance;
            }

            return instance;
        }

        public static Service GetInstance<Service>(params object[] args) where Service : BaseClass
        {
            _instance = null;
            Service instance = null;
            Type type = typeof(Service);
            string typeName = type.Name;
            if (_instance == null)
            {
                _instance = new Dictionary<string, BaseClass>();
            }
            if (_instance.Keys.Contains(typeName))
            {
                instance = _instance[typeName] as Service;
            }
            else
            {
                if (args.Count() > 0)
                {
                    instance = type.Assembly.CreateInstance(type.FullName, true, BindingFlags.Default, null, args, CultureInfo.CurrentCulture, null) as Service;
                }
                else
                {
                    instance = type.Assembly.CreateInstance(type.FullName) as Service;
                }
                _instance[typeName] = instance;
            }

            return instance;
        }
    }
}
